#include "at32_board.h"
#include "stdio.h"
#ifdef __cplusplus
namespace std
{
  extern "C" {
#endif

/* Suport printf function, useMicroLib is unnecessary */
//#ifdef __CC_ARM
//  #pragma import(__use_no_semihosting)
//  struct __FILE
//  {
//    int handle;
//  };
//  
//  FILE __stdout;
//  
//  void _sys_exit(int x)
//  {
//    x = x;
//  }
//#endif

//#ifdef __GNUC__
//  /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
//     set to 'Yes') calls __io_putchar() */
//  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
//#else
//  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
//#endif /* __GNUC__ */

/**
  * @brief  Retargets the C library printf function to the USART.
  * @param  None
  * @retval None
  */
//PUTCHAR_PROTOTYPE
//{  
//  USART_SendData(AT32_PRINT_UART, ch);
//  while ( USART_GetFlagStatus(AT32_PRINT_UART, USART_FLAG_TRAC) == RESET );    
//  return ch;
//}

#ifdef __cplusplus
  } /* extern "C" */
} /* namespace */
#endif

/*delay macros*/
#define STEP_DELAY_MS	50
/*delay variable*/
static __IO uint32_t fac_us;
static __IO uint32_t fac_ms;
 
/**
  * @brief  Board initialize interface 
  *         init LED and BUTTON
  * @param  None
  * @retval None
  */
void AT32_Board_Init()
{
  /*initialize Delay Function*/
//  Delay_init();

}

/**
  * @brief  initialize Delay function   
  * @param  None
  * @retval None
  */		   
void Delay_init()
{
  /*Config Systick*/
  SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);
  fac_us = SystemCoreClock / (1000000U);
  fac_ms = fac_us * (1000U);
}

/**
  * @brief  Inserts a delay time.
  * @param  nus: specifies the delay time length, in microsecond.
  * @retval None
  */
//void Delay_us(u32 nus)
//{
//  u32 temp;
//  SysTick->LOAD = (u32)(nus*fac_us);
//  SysTick->VAL = 0x00;
//  SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk ;
//  do
//  {
//    temp = SysTick->CTRL;
//  }while((temp & 0x01) &&! (temp & (1<<16)));

//  SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
//  SysTick->VAL = 0X00;
//}

///**
//  * @brief  Inserts a delay time.
//  * @param  nms: specifies the delay time length, in milliseconds.
//  * @retval None
//  */
//void Delay_ms(u16 nms)
//{
//  u32 temp;
//  while(nms)
//  {
//    if(nms > STEP_DELAY_MS)
//    {
//      SysTick->LOAD = (u32)(STEP_DELAY_MS * fac_ms);
//      nms -= STEP_DELAY_MS;
//    }
//    else
//    {
//      SysTick->LOAD = (u32)(nms * fac_ms);
//      nms = 0;
//    }
//    SysTick->VAL = 0x00;
//    SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;
//    do
//    {
//      temp = SysTick->CTRL;
//    }while( (temp & 0x01) && !(temp & (1<<16)) );

//    SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
//    SysTick->VAL = 0X00;
//  }
//}

///**
//  * @brief  Inserts a delay time.
//  * @param  sec: specifies the delay time length, in seconds.
//  * @retval None
//  */
//void Delay_sec(u16 sec)
//{
//  u16 i;
//  for(i=0; i<sec; i++)
//  {
//    Delay_ms(500);
//    Delay_ms(500);
//  }
//}
//	





